<template>
	<view class="addContract">
		<uni-forms ref="valiForm">
			<view class="contractContent">
				<view class="content_title"><text>*</text>基本信息</view>
				<view class="formLabel uni-flex border-bottom uni-justify-between">
					<text class="form_label">姓名</text>
					<text class="form_data">{{ Signidentity?.fullName ||
						'--' }}（{{ Signidentity?.isRealName || '' === 'YES' ? "已认证" : "未认证" }}）</text>
				</view>
				<view class="formLabel uni-flex border-bottom uni-justify-between" @click="goRealName">
					<text class="form_label">证件类型</text>
					<view class="uni-flex uni-align-center form_select">身份证<uni-icons type="right" size="15"
							style="margin-left:24rpx;"></uni-icons></view>
				</view>
				<view class="formLabel uni-flex border-bottom uni-justify-between">
					<text class="form_label">身份证号</text>
					<text class="form_data">{{ Signidentity?.idCard || '--' }}</text>
				</view>
				<view class="formLabel uni-flex border-bottom uni-justify-between" @click="showPhoneBind">
					<text class="form_label">联系方式</text>
					<view class="uni-flex uni-align-center form_select">
						{{ Signidentity?.phone || '--' }}
						<text>{{Signidentity?.phone!==null||Signidentity?.phone!==""?'（已绑定）':'（未绑定）'}}</text> <uni-icons
							type="right" size="15" style="margin-left:24rpx;"></uni-icons>
					</view>
				</view>
				<view class="formLabel uni-flex uni-justify-between" @click="showPosition">
					<text class="form_label">当前住址</text>
					<view class="uni-flex uni-align-center form_select"
						:style="{color: currentAddress === '请选择地址' ? '#999999' : '#333333'}">
						{{ currentAddress }}<uni-icons type="right" size="15" style="margin-left:24rpx;"></uni-icons>
					</view>
				</view>
			</view>
			<view class="contractContent">
				<view class="content_title"><text>*</text>服务信息</view>
				<view class="uni-flex uni-justify-between uni-align-center service-box">
					<view class="service-title">服务范围</view>
					<view class="uni-flex uni-align-center service-btn" @click="showService"
						v-if="userType!=='FREE_SERVER'"><uni-icons type="plus" size="18"
							color="#999999"></uni-icons>添加服务项</view>
				</view>
				<view>
					<view class="service-tags uni-flex uni-flex-wrap">
						<view v-for="(tag, index) in tags" :key="tag.id" class="service-tag">
							<text>{{ tag.name }}</text>
							<uni-icons class="delete-icon" type="closeempty" size="14" color="#999999"
								@click="removeTag(index)" style="margin-left:10rpx" />
						</view>
					</view>
				</view>
				<view class="uni-flex uni-justify-between uni-align-center service-box">
					<view class="service-title">期望服务区域</view>
					<view class="uni-flex uni-align-center service-btn" @click="showArea"
						v-if="userType!=='FREE_SERVER'">
						<uni-icons type="plus" size="18" color="#999999"></uni-icons>添加区域
					</view>
				</view>
				<view>
					<view class="service-tags uni-flex uni-flex-wrap">
						<view v-for="(area, index) in selectedAreas" :key="area.provinceCode" class="service-tag">
							<text>{{ formatAreaName(area) }}</text>
							<uni-icons class="delete-icon" type="closeempty" size="14" color="#999999"
								@click="removeArea(index)" style="margin-left:10rpx" />
						</view>
					</view>
				</view>
			</view>
			<view class="contractContent2">
				<view class="uni-flex uni-justify-between uni-align-center content_title2">
					<view><text>*</text>服务经历</view>
					<uni-icons type="plus" size="20" color="#666666" @click="showExperience"></uni-icons>
				</view>
				<view class="serviceExperience" v-for='(item, index) in ServiceList' :key="index">
					<view class="serviceExperience-content uni-flex uni-justify-between uni-align-center">
						<view class="serviceExperience-title">{{item.title}}</view>
						<view class="serviceExperience-time" @click="goEditService(item)">
							{{ item.startDate }}-{{ item.endDate }}<uni-icons type="right" size="15"
								style="margin-left:16rpx;" color="#666666"></uni-icons>
						</view>
					</view>
					<view class="serviceExperience-desc">
						{{ item.content }}
					</view>
					<view class="serviceExperience-imgs uni-flex uni-flex-wrap">
						<image v-for="(img, imgIndex) in (item.tempImgUrls || item.imgFullUrls || '').split(',')"
							:key="imgIndex" :src="img" class="serviceExperience-img" mode="aspectFill" />
					</view>
				</view>

			</view>

			<view class="contractContent" v-if='contractType === "2"'>
				<view class="uni-flex uni-justify-between uni-align-center content_title">
					<view>技能证书</view>
					<!-- <uni-icons type="plus" size="20" color="#666666" @click="showCertificate"></uni-icons> -->
				</view>
				<view class="certificate-imgs uni-flex uni-flex-wrap">
					<view class="certificate-img-box" v-for="(item, index) in SkillList" :key="index">
						<!-- 有图片时显示图片和删除按钮 -->
						<template v-if="item.userCertImageUrl || item.tempImgUrl || item.imgFullUrl">
							<view class="image-container">
								<!-- 优先显示 userCertImageUrl，如果没有则显示临时路径或云端路径 -->
								<image :src="item.userCertImageUrl || item.tempImgUrl || item.imgFullUrl"
									mode="aspectFill" class="certificate-img" />
								<view class="delete-btn" @click.stop="removeImage(index,item.id)">
									<uni-icons type="closeempty" size="16" color="#fff"></uni-icons>
								</view>
							</view>
						</template>
						<!-- 无图片时显示上传区域 -->
						<template v-else>
							<view class="upload-area" @click="chooseImageHandler(index)">
								<image :src="`${$ImgBaseUrl}contract-camera.png`" mode="widthFix" class="camera" />
							</view>
						</template>

						<!-- 证书标题 -->
						<view class="certificate-img-title">{{ item.certName || '未命名证书' }}</view>
					</view>
				</view>
			</view>
		</uni-forms>
		<view class="uni-flex uni-align-center xy-box" style="margin-top:47rpx;">
			<checkbox style="transform:scale(0.7);" @click="() => isCheckedAgreement = !isCheckedAgreement"
				color="#2F80ED" backgroundColor="#EEF5FF" borderColor="#999999" activeBackgroundColor="#EEF5FF"
				activeBorderColor="#2F80ED" iconColor="#2F80ED" />
			<view class="checkbox-label">
				请阅读并确认
				<text class="blue_link">《零付-零工服务合作协议》</text>
			</view>
		</view>
		<view class="uni-flex uni-align-center xy-box">
			<checkbox style="transform:scale(0.7);" @click="() => isCheckedNotice = !isCheckedNotice" color="#2F80ED"
				backgroundColor="#EEF5FF" borderColor="#999999" activeBackgroundColor="#EEF5FF"
				activeBorderColor="#2F80ED" iconColor="#2F80ED" />
			<view class="checkbox-label">
				请阅读并确认
				<text class="blue_link">《零付APP使用须知》</text>
			</view>
		</view>

		<view class="contract-button" @click="submit('valiForm')">提交签约申请</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onUnmounted,
		watch,
		getCurrentInstance,
		onMounted
	} from "vue";
	import {
		getServiceList,
		addFree,
		addSign,
		getSignInfo,
		addService,
		addOrEditSkillCert,
		skillCertsList,
		deleteSkillCert

	} from '@/api/contract.js'
	import {
		qiNiuFileUpload
	} from "@/utils/qiniu.js";
	import {
		onShow,
		onLoad
	}
	from '@dcloudio/uni-app';
	import {
		startEid
	} from '@/mp_ecard_sdk/main';
	import {
		getEToken,
		pushEToken,
		userInfo
	} from "@/api/user.js";
	const ServiceList = ref([])
	const selectedAreas = ref([]); // 存储选择的区域
	const basicInfo = ref()
	const SkillList = ref([])
	const contractType = ref()
	const isCheckedAgreement = ref(false); // 《零付-零工服务合作协议》
	const isCheckedNotice = ref(false); // 《零付APP使用须知》
	const addressId = ref('')
	const Signidentity = ref('')
	const isChecked = ref(false);
	const tags = ref([]);
	const currentAddress = ref("请选择地址"); // 默认显示文本
	const savedAddressId = ref('')
	const userid = ref('')
	// 存储是否必传技能证书的状态
	const isSkillCertRequired = ref(false);
	// 用于存储 signAuditStatus
	const signAuditStatus = ref('');
	const userType = ref('')
	onLoad((options) => {
		// 接收上个页面传过来的type,判断是否显示技能证书
		contractType.value = options.type
	})
	onMounted(() => {
		const pages = getCurrentPages();
		const currentPage = pages[pages.length - 1];
		const query = currentPage.options;
		savedAddressId.value = uni.getStorageSync('savedAddressId');
		const userinfo = uni.getStorageSync("user_info");
		let userInfoData = {};
		if (userinfo) {
			userid.value = JSON.parse(userinfo).id;
			userInfoData = JSON.parse(userinfo);
			userType.value = JSON.parse(userinfo).userType
		}
		console.log('userType.value', userType.value);
		const {
			busMobileUserService = {}
		} = userInfoData;
		signAuditStatus.value = busMobileUserService.signAuditStatus;
		loadServiceList()
		// loadSkillList()
		loadSignInfo()
		// skillCertsListApi(); // 加载技能证书列表

	});
	// 服务经历列表
	const loadServiceList = () => {
		return getServiceList().then((res) => { // 返回 Promise 方便 await 等待
			console.log('服务列表接口返回数据:', res); // 调试接口原始数据
			if (res.code === 200 && Array.isArray(res.rows)) {
				// 确保每条记录都包含真实 ID（重点检查 id 字段）
				ServiceList.value = res.rows.map(item => ({
					...item,
					id: item.id || item.resumeId, // 兼容可能的字段名（如后端用 resumeId 存储 ID）
					tempImgUrls: item.imgFullUrls || ""
				}));
				console.log('刷新后的服务经历列表（含真实ID）:', ServiceList.value);
			} else {
				// 处理接口返回异常（如非数组）
				ServiceList.value = [];
				console.error('服务列表接口返回格式错误:', res);
			}
		}).catch(err => {
			console.error('加载服务经历失败:', err);
			ServiceList.value = [];
		});
	};


	const skillCertsListApi = () => {
		// 从 tags 数组中提取所有 id（优先使用 serviceItemId，不存在则用 id）
		const categoryIds = tags.value.map(tag => tag.serviceItemId || tag.id).join(',');
		skillCertsList(categoryIds)
			.then((res) => {
				console.log('技能证书列表:', res);
				if (res.code === 200) {
					// 更新技能证书列表
					SkillList.value = res.data.certs || [];
					// 保存是否必传的状态
					isSkillCertRequired.value = res.data.isRequiredCert === 1;
				} else {
					console.error('接口返回错误:', res.msg);
					uni.showToast({
						title: res.msg || '获取技能证书失败',
						icon: 'none'
					});
				}
			})
			.catch(err => {
				console.error('请求技能证书失败:', err);
				uni.showToast({
					title: '请求技能证书失败，请重试',
					icon: 'none'
				});
			});
	};

	// 获取签约信息
	const loadSignInfo = () => {
		getSignInfo().then((res) => {
			console.log('签约信息', res);
			if (res.code === 200) {
				Signidentity.value = res.data;
				console.log('Signidentity.value', Signidentity.value);
				// 修改这里的地址逻辑
				const hasAddress = Signidentity.value.provinceLive || Signidentity.value.cityLive ||
					Signidentity.value.addressLive;
				currentAddress.value = hasAddress ?
					`${Signidentity.value.provinceLive || ''}${Signidentity.value.cityLive || ''}${Signidentity.value.addressLive || ''}` :
					'请选择当前住址';

				// 期望服务区域
				if (Signidentity.value.sysAreas && Signidentity.value.sysAreas.length > 0) {
					selectedAreas.value = Signidentity.value.sysAreas.map(area => ({
						cityCode: area.areaId,
						cityName: area.areaName,
						provinceCode: area.parentId,
						provinceName: area.areaNames.split(',')[0]
					}));
				}

				// 服务范围
				if (Signidentity.value.cfgServiceItems && Signidentity.value.cfgServiceItems.length > 0) {
					tags.value = Signidentity.value.cfgServiceItems.map(service => ({
						id: service.id,
						name: service.itemName,
						// serviceItemId: service.id
					}));
				}
			}

			// 只有当服务范围不为空时才调用 skillCertsListApi
			if (tags.value && tags.value.length > 0) {
				skillCertsListApi();
			} else {
				console.log('服务范围为空，不调用技能证书接口');
				SkillList.value = []; // 清空技能证书列表
			}
		});
	}

	// 更新服务经历列表
	const updateServiceExperience = (newExperience) => {
		// 确保新数据包含临时图片路径和真实图片路径
		const updatedItem = {
			...newExperience,
			tempImgUrls: newExperience.tempImgUrls || newExperience.imgFullUrls || '', // 显示用临时路径
			imgFullUrls: newExperience.imgFullUrls || '' // 提交用真实路径
		};

		if (newExperience.id && newExperience.id.toString().startsWith('temp_')) {
			// 新增项（临时ID）
			ServiceList.value.unshift(updatedItem);
		} else {
			// 编辑已有项
			const index = ServiceList.value.findIndex(item => item.id === newExperience.id);
			if (index !== -1) {
				ServiceList.value[index] = updatedItem;
			}
		}
		// 触发响应式更新
		ServiceList.value = [...ServiceList.value];
	};

	// 暴露方法给模板
	defineExpose({
		updateServiceExperience
	});
	// 跳转到编辑服务经历页面
	const goEditService = (item) => {
		if (userType.value !== 'FREE_SERVER') {
			uni.navigateTo({
				url: `/pages/tabBars/serviceExperience/serviceExperience`,
				events: {
					acceptDataFromOpenedPage: (data) => {
						console.log('data', data)
						if (data.type === 'serviceExperience') {
							updateServiceExperience(data.data);
						}
					}
				},
				success: (res) => {
					// 传递当前项的数据（包括临时图片路径）
					console.log('res', res)
					res.eventChannel.emit('acceptDataFromOpenerPage', {
						item: {
							...item,
							tempImgUrls: item.tempImgUrls || item.imgFullUrls || '' // 优先用临时路径
						}
					});
				}
			});
		} else {
			uni.showToast({
				icon: 'none',
				title: '您已成为自由服务者，无法在此修改服务经历！'
			})
			return
		}

	};

	// 图片选择处理（修改为七牛云上传）
	const chooseImageHandler = async (index) => {
		// 判断 signAuditStatus 是否为 "IN_REVIEW"
		if (signAuditStatus.value === "IN_REVIEW") {
			uni.showToast({
				title: '签约服务者信息审核中，无法修改！！！',
				icon: 'none'
			});
			return; // 阻止后续修改操作执行
		}


		try {
			// 检查 SkillList.value[index] 是否存在
			if (!SkillList.value[index]) {
				console.error('SkillList item at index is undefined:', index);
				return;
			}

			const res = await uni.chooseImage({
				count: 1,
				sizeType: ["original", "compressed"],
				sourceType: ["album", "camera"]
			});

			if (res.tempFilePaths && res.tempFilePaths.length > 0) {
				uni.showLoading({
					title: '上传中...'
				});
				const filePath = res.tempFilePaths[0];
				const cloudPath = `images/cert/${userid.value}/${Date.now()}_${index}.png`;

				// 更新临时路径
				SkillList.value = SkillList.value.map((item, i) =>
					i === index ? {
						...item,
						tempImgUrl: filePath,
						imgFullUrl: cloudPath,
						isTemp: true
					} : item
				);

				await qiNiuFileUpload(
					[{
						path: filePath,
						key: cloudPath
					}],
					async (keys) => {
							uni.hideLoading();
							uni.showToast({
								title: '上传成功',
								icon: 'success'
							});

							try {
								const certRes = await addOrEditSkillCert({
									certType: SkillList.value[index].id,
									certImages: cloudPath,
								});

								if (certRes.code === 200) {

									skillCertsListApi()
								} else {
									throw new Error(certRes.msg || '证书保存失败');
								}
							} catch (error) {
								console.error('保存证书失败:', error);
								uni.showToast({
									title: '保存证书失败',
									icon: 'none'
								});
							}
						},
						(error) => {
							uni.hideLoading();
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							});
							console.error('上传失败:', error);
						}
				);
			}
		} catch (error) {
			uni.hideLoading();
			console.error('选择图片失败:', error);
		}
	};

	// 删除图片
	const removeImage = (index, id) => {
		// console.log('id', id);
		// 判断 signAuditStatus 是否为 "IN_REVIEW"
		if (signAuditStatus.value === "IN_REVIEW") {
			uni.showToast({
				title: '签约服务者信息审核中，无法修改！！！',
				icon: 'none'
			});
			return; // 阻止后续删除操作执行
		}

		// 先调用接口删除
		deleteSkillCert(id).then(res => {
			if (res.code === 200) {
				// 接口成功后再更新本地数据
				SkillList.value = SkillList.value.map((item, i) => {
					if (i === index) {
						return {
							...item,
							userCertImageUrl: '', // 清除服务器返回的图片URL
							imgFullUrl: '',
							isTemp: false
						};
					}
					return item;
				});
				uni.showToast({
					title: res.msg || '删除成功',
					icon: 'success'
				});
			} else {
				uni.showToast({
					title: res.msg || '删除失败',
					icon: 'none'
				});
			}
		}).catch(err => {
			uni.showToast({
				title: res.msg || '删除失败，请重试',
				icon: 'none'
			});
		});
	};
	const showPosition = () => {
		// if (Signidentity.value.userType === "FREE_SERVER") {
		// 	uni.showToast({
		// 		icon: 'none',
		// 		title: '您已成为自由服务者，无法在此修改基本信息！'
		// 	})
		// 	return
		// } else {

		uni.navigateTo({
			url: '/pages/tabBars/serviceAddress/serviceAddress',
			events: {
				// 监听地址选择事件
				acceptDataAddress: (data) => {
					console.log('接收到地址数据:', data);
					addressId.value = data.id
					// 更新当前地址显示
					currentAddress.value =
						`${data.provinceLive || ''}${data.landmark || ''}`;
				}
			}
		});
		// }


	};
	// 打开技能证书页面
	const showCertificate = () => {
		uni.navigateTo({
			url: '/pages/tabBars/skillCertificate/skillCertificate',
			events: {
				// 接收从证书页面返回的临时数据
				certSaved: (data) => {
					if (data.cert) {
						SkillList.value.push(data.cert);
					}
				}
			}
		})
	};
	// 添加接收服务项的方法
	const updateSelectedServices = (services) => {
		// 确保数据结构正确
		tags.value = services.map(item => ({
			id: item.id || `custom_${Date.now()}`,
			name: item.name,
			serviceItemId: item.serviceItemId || null
		}))

		console.log('更新后的tags:', tags.value) // 调试用
	}

	// 修改showService方法
	const showService = () => {
		uni.navigateTo({
			url: '/pages/contract/addService',
			events: {
				acceptDataFromOpenedPage: function(data) {
					try {
						tags.value = data.selectedServices || [];
						console.log('服务项已更新:', tags.value);
						// 如果服务范围不为空，调用接口
						if (tags.value.length > 0) {
							skillCertsListApi();
						} else {
							SkillList.value = [];
						}
					} catch (error) {
						console.error('处理返回的服务数据出错:', error);
						uni.showToast({
							title: '处理服务数据出错',
							icon: 'none'
						});
					}
				}
			},
			success: (res) => {
				res.eventChannel.emit('acceptDataFromOpenerPage', {
					selectedServices: tags.value.map(tag => ({
						id: tag.id,
						serviceItemId: tag.serviceItemId || tag.id,
						name: tag.name
					}))
				});
			}
		});
	};
	const showPhoneBind = () => {
		// if (Signidentity.value.userType === "FREE_SERVER") {
		// 	uni.showToast({
		// 		icon: 'none',
		// 		title: '您已成为自由服务者，无法在此修改基本信息！'
		// 	})
		// 	return
		// }
		// else {
		const currentPhone = Signidentity.value?.phone || '';
		// console.log('currentPhone',currentPhone);
		uni.navigateTo({
			url: `/pages/tabBars/bindPhone/phone?phone=${encodeURIComponent(currentPhone)}`
		})
		// }

	};
	// 格式化显示名称，确保无空值
	const formatAreaName = (area) => {
		// 若areaName为空（如省级），直接显示省份名
		if (!area.areaName || area.areaName.trim() === '') {
			return `${area.provinceName}·${area.cityName}` || '未知区域'
		}
		// 区县级显示“城市·区域”（如“广州市·天河区”）
		if (area.cityName && area.areaName && area.cityName !== area.areaName) {
			return `${area.cityName}·${area.areaName}`;
		}
		// 市级/省级直接显示名称（如“广州市”或“广东省”）
		return area.areaName;
	};
	const showArea = () => {
		uni.navigateTo({
			url: '/pages/tabBars/selectAddress/selectAddress',
			events: {
				acceptDataFromOpenedPage: function(data) {
					console.log('接收到的完整区域数据:', data); // 调试用

					selectedAreas.value = data.selectedAreas.map(area => ({
						cityCode: area.cityCode,
						cityName: area.cityName,
						// 兼容多种可能的字段名
						areaName: area.areaName,
						provinceName: area.provinceName,
						provinceCode: area.provinceCode
					}));
				}
			},
			success: (res) => {
				res.eventChannel.emit('acceptDataFromOpenerPage', {
					selectedAreas: selectedAreas.value.map(area => ({
						cityCode: area.cityCode,
						cityName: area.cityName,
						areaName: area.areaName, // 确保传递当前值
						provinceName: area.provinceName,
						provinceCode: area.provinceCode
					}))
				});
			}
		});
	};
	// 移除区域
	const removeArea = (index) => {
		if (userType.value !== 'FREE_SERVER') {
			selectedAreas.value.splice(index, 1);
		} else {
			uni.showToast({
				icon: 'none',
				title: '您已成为自由服务者，无法在此修改期望服务区域！'
			})
			return
		}

	};
	const showExperience = () => {
		if (userType.value !== 'FREE_SERVER') {
			uni.navigateTo({
				url: '/pages/tabBars/serviceExperience/serviceExperience',
				events: {
					// 监听从服务经历页面返回的数据
					acceptDataFromOpenedPage: function(data) {
						if (data.type === 'serviceExperience') {
							// 将服务经历添加到列表中
							updateServiceExperience(data.data);
						}
					}
				}
			})
		} else {
			uni.showToast({
				icon: 'none',
				title: '您已成为自由服务者，无法在此添加服务经历！'
			})
			return
		}

	};

	const goRealName = () => {
		// if (Signidentity.value.userType === "FREE_SERVER") {
		// 	uni.showToast({
		// 		icon: 'none',
		// 		title: '您已成为自由服务者，无法在此修改基本信息！'
		// 	})
		// 	return
		// }

		getEToken().then(res => {
			const {
				eidToken
			} = res.data;
			console.log('获取token成功:', eidToken);
			startEid({
				data: {
					token: eidToken,
					enableEmbedded: true,
					allowFullScreen: false
				},
				verifyDoneCallback(res) {
					const {
						token,
						verifyDone
					} = res;
					console.log('收到核身完成的res:', res);
					console.log('核身的token是:', token);
					console.log('是否完成核身:', verifyDone);
					pushEToken({
						faceToken: token
					}).then(res => {
						console.log('上传token成功:', res);
						uni.showToast({
							icon: "none",
							title: "实名认证成功",
						});
						userInfo().then((res) => {
							if (res.code == 200) {
								Signidentity.value.fullName = res.data
									.busMobileUserService.fullName
								Signidentity.value.isRealName = res.data
									.busMobileUserService.isRealName
								Signidentity.value.idCard = res.data
									.busMobileUserService.idCard
								store.commit('setUserInfo', res.data)
							} else {
								uni.showToast({
									icon: "none",
									title: res.msg,
								});
							}
						});
					})
				},
			});
		})
		// }

	}

	const removeTag = (index) => {
		if (userType.value !== 'FREE_SERVER') {
			tags.value.splice(index, 1)
			skillCertsListApi();
			
		} else {
			uni.showToast({
				icon: 'none',
				title: '您已成为自由服务者，无法在此修服务范围！'
			})
			return
		}

	};
	const onCheckChange = () => {
		isChecked.value = !isChecked.value
	};

	// 提交签约申请按钮
	const submit = async (ref) => {
		// 1. 基础校验
		if (!isCheckedAgreement.value) {
			uni.showToast({
				icon: 'none',
				title: '请先阅读并同意《零付-零工服务合作协议》'
			});
			return;
		}
		if (!isCheckedNotice.value) {
			uni.showToast({
				icon: 'none',
				title: '请先阅读并同意《零付APP使用须知》'
			});
			return;
		}
		if (!ServiceList.value || ServiceList.value.length === 0) {
			uni.showToast({
				icon: 'none',
				title: '请至少添加一条服务经历'
			});
			return;
		}
		// 新增：技能证书必传校验
		if (contractType.value === "2") {
			// 检查是否有证书项未上传图片
			const invalidCerts = SkillList.value.filter(item =>
				!item.userCertImageUrl && !item.tempImgUrl && !item.imgFullUrl
			);

			if (invalidCerts.length > 0) {
				uni.showToast({
					icon: 'none',
					title: `请上传${invalidCerts.map(c => c.certName).join('、')}的证书图片`
				});
				return;
			}
		}

		try {
			uni.showLoading({
				title: '提交中...'
			});

			// 6. 刷新服务经历列表
			await loadServiceList();

			// 7. 构造最终提交参数
			const finalAddressId = addressId.value || savedAddressId.value;
			const paramsAddFree = {
				services: tags.value.map(tag => tag.serviceItemId || tag.id),
				addressId: finalAddressId,
				cityCodes: selectedAreas.value.map(area => area.cityCode),
				resumeIds: ServiceList.value
					.filter(item => item.id && !item.id.toString().startsWith('temp_'))
					.map(item => item.id)
			};

			const paramsAddSign = {
				...paramsAddFree,
				// skillCerts: [...SkillList.value.filter(cert => !cert.isTemp).map(cert => cert.id), ...certIds]
			};

			// 8. 根据类型调用最终提交接口（关键修复）
			console.log('开始调用最终提交接口，类型：', contractType.value);
			const finalRes = contractType.value === '1' ?
				await addFree(paramsAddFree) :
				await addSign(paramsAddSign);

			if (finalRes.code === 200) {
				uni.showToast({
					title: finalRes.msg || '提交成功', // 修复：使用finalRes而非res
					icon: 'success'
				});
				setTimeout(() => uni.navigateBack(), 1500);
			} else {
				throw new Error(finalRes.msg || '签约申请提交失败');
			}

		} catch (error) {
			console.error('提交流程失败:', error);
			// 修复：使用error.message而非res.msg
			uni.showToast({
				icon: 'none',
				title: res.msg || '提交失败，请重试'
			});
		} finally {
			uni.hideLoading();
		}
	};
</script>
<style scoped lang="scss">
	.addContract {
		padding: 26rpx 24rpx 101rpx;
		background: #F5F5F5;
		min-height: calc(100vh - 26rpx);

		.contractContent {
			background: #FFFFFF;
			border-radius: 20rpx;
			padding: 28rpx 25rpx 0 23rpx;
			margin-bottom: 24rpx;

			.certificate-img-box {
				display: flex;
				flex-direction: column;
				align-items: center;
				width: 47%;
				margin: 0 0 20rpx 0;
				position: relative;
				height: 254rpx;

				.image-container {
					position: absolute;
					top: 0;
					left: 0;
					width: 100%;
					height: 205rpx;
					border-radius: 16rpx 16rpx 0 0;
					overflow: hidden;

					.certificate-img {
						width: 100%;
						height: 100%;
						object-fit: cover;
						border-top-left-radius: 16rpx;
						border-top-right-radius: 16rpx;
					}

					.delete-btn {
						position: absolute;
						top: 10rpx;
						right: 10rpx;
						width: 40rpx;
						height: 40rpx;
						background: rgba(0, 0, 0, 0.5);
						border-radius: 50%;
						display: flex;
						align-items: center;
						justify-content: center;
						z-index: 10;
					}
				}

				.upload-area {
					position: absolute;
					top: 0;
					left: 0;
					width: 100%;
					height: 205rpx;
					background: #F4F5F7;
					border-radius: 16rpx 16rpx 0 0;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;

					.camera {
						width: 48rpx;
						height: 43rpx;
					}
				}

				.certificate-img-title {
					width: 100%;
					height: 49rpx;
					background: #E7F1FF;
					text-align: center;
					font-weight: 500;
					font-size: 24rpx;
					line-height: 49rpx;
					color: #2F80ED;
					border-radius: 0 0 16rpx 16rpx;
					position: absolute;
					bottom: 0;
					left: 0;
					z-index: 5;
				}
			}

			.certificate-img-box:nth-child(odd) {
				margin-right: 33rpx;
			}

			.serviceExperience {
				.serviceExperience-content {
					.serviceExperience-title {
						font-weight: 500;
						font-size: 28rpx;
						color: #303133;
					}

					.serviceExperience-time {
						font-weight: 400;
						font-size: 24rpx;
						color: #999999;
					}
				}

				.serviceExperience-desc {
					margin: 24rpx 0 16rpx;
					font-weight: 400;
					font-size: 28rpx;
					color: #303133;
				}

				.serviceExperience-img {
					width: 220rpx;
					height: 151rpx;
					border-radius: 16rpx;
					margin: 0 21rpx 21rpx 0;
				}
			}

			.service-box {
				margin-top: 12rpx;

				.service-title {
					font-weight: 400;
					font-size: 28rpx;
					color: #303133;
				}

				.service-btn {
					border-radius: 24rpx;
					border: 1rpx dashed #D8D8D8;
					padding: 8rpx 14rpx;
					font-weight: 400;
					font-size: 24rpx;
					color: #999999;
				}
			}

			.service-tags {
				margin-top: 20rpx;

				.service-tag {
					padding: 15rpx 19rpx;
					background: #F1F1F1;
					border-radius: 6rpx;
					font-weight: 400;
					font-size: 28rpx;
					color: #333333;
					margin: 0 20rpx 20rpx 0;
				}
			}

			.content_title {
				font-weight: 500;
				font-size: 32rpx;
				color: #303133;
				margin-bottom: 27rpx;

				text {
					color: #EB4747;
				}
			}

			.content_title2 {
				font-weight: 500;
				font-size: 32rpx;
				color: #303133;

				text {
					color: #EB4747;
				}
			}

			.border-bottom {
				border-bottom: 1px solid #E2E2E2;
			}

			.formLabel {
				.form_label {
					font-weight: 400;
					font-size: 28rpx;
					color: #303133;
				}

				.form_data {
					font-weight: 400;
					font-size: 28rpx;
					color: #999999;
				}

				.form_select {
					font-weight: 400;
					font-size: 28rpx;
					color: #333333;
				}

				text {
					line-height: 120rpx;
				}
			}
		}

		// 关键修复：添加 .contractContent 的闭合括号

		.contractContent2 {
			background: #FFFFFF;
			border-radius: 20rpx;
			padding: 20rpx;
			margin-bottom: 24rpx;

			.certificate-img-box {
				width: 47%;
				height: 205rpx;
				margin: 0 0 20rpx 0;
				position: relative;
				border-radius: 16rpx;

				.certificate-img {
					width: 100%;
					height: 100%;
					border-radius: 16rpx;
				}

				.certificate-img-title {
					position: absolute;
					bottom: 0;
					left: 0;
					width: 100%;
					height: 49rpx;
					background: #E7F1FF;
					text-align: center;
					font-weight: 500;
					font-size: 24rpx;
					line-height: 49rpx;
					color: #2F80ED;
					border-radius: 0 0 16rpx 16rpx;
				}
			}

			.certificate-img-box:nth-child(odd) {
				margin-right: 33rpx;
			}

			.serviceExperience {
				.serviceExperience-content {
					.serviceExperience-title {
						font-weight: 500;
						font-size: 28rpx;
						color: #303133;
					}

					.serviceExperience-time {
						font-weight: 400;
						font-size: 24rpx;
						color: #999999;
					}
				}

				.serviceExperience-desc {
					margin: 24rpx 0 16rpx;
					font-weight: 400;
					font-size: 28rpx;
					color: #303133;
				}

				.serviceExperience-img {
					width: 220rpx;
					height: 151rpx;
					border-radius: 16rpx;
					margin: 0 21rpx 21rpx 0;
				}
			}

			.service-box {
				margin-top: 12rpx;

				.service-title {
					font-weight: 400;
					font-size: 28rpx;
					color: #303133;
				}

				.service-btn {
					border-radius: 24rpx;
					border: 1rpx dashed #D8D8D8;
					padding: 8rpx 14rpx;
					font-weight: 400;
					font-size: 24rpx;
					color: #999999;
				}
			}

			.service-tags {
				margin-top: 20rpx;

				.service-tag {
					padding: 15rpx 19rpx;
					background: #F1F1F1;
					border-radius: 6rpx;
					font-weight: 400;
					font-size: 28rpx;
					color: #333333;
					margin: 0 20rpx 20rpx 0;
				}
			}

			.content_title {
				font-weight: 500;
				font-size: 32rpx;
				color: #303133;
				margin-bottom: 27rpx;

				text {
					color: #EB4747;
				}
			}

			.content_title2 {
				font-weight: 500;
				font-size: 32rpx;
				color: #303133;

				text {
					color: #EB4747;
				}
			}

			.border-bottom {
				border-bottom: 1px solid #E2E2E2;
			}

			.formLabel {
				.form_label {
					font-weight: 400;
					font-size: 28rpx;
					color: #303133;
				}

				.form_data {
					font-weight: 400;
					font-size: 28rpx;
					color: #999999;
				}

				.form_select {
					font-weight: 400;
					font-size: 28rpx;
					color: #333333;
				}

				text {
					line-height: 120rpx;
				}
			}
		}

		.xy-box {
			padding: 0 0 0 69rpx;
			margin: 0 0 29rpx;
		}

		.checkbox-label {
			font-weight: 400;
			font-size: 28rpx;
			color: #999999;

			.blue_link {
				color: #2f80ed;
			}
		}

		.contract-button {
			width: 86%;
			height: 88rpx;
			background: #2F80ED;
			border-radius: 44rpx;
			text-align: center;
			font-weight: 600;
			font-size: 30rpx;
			color: #FFFFFF;
			line-height: 88rpx;
			margin: 47rpx auto 0;
		}
	}
</style>